package com.summer.peony.sso.service.impl;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DigestUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.summer.peony.common.entity.AjaxResult;
import com.summer.peony.common.entity.AjaxResult.Type;
import com.summer.peony.sso.service.LoginService;
import com.summer.peony.system.mapper.SysUserMapper;
import com.summer.peony.system.pojo.SysUser;
import com.summer.peony.system.pojo.SysUserExample;
import com.summer.peony.system.pojo.SysUserExample.Criteria;

@Service
@PropertySource("classpath:application.yml")
public class LoginServiceImpl implements LoginService {

	@Value("${SESSION.SESSION_EXPIRE}")
	private String SESSION_EXPIRE;

	@Autowired
	private SysUserMapper sysUserMapper;

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@Override
	public AjaxResult userLogin(String username, String password) {
		// TODO 用户登录
		AjaxResult ajaxResult = new AjaxResult();
		// 参数：用户名和密码
		// 业务逻辑：
//		 1、判断用户名和密码是否正确
		// 设置查询条件
		SysUserExample example = new SysUserExample();
		Criteria criteria = example.createCriteria();
		criteria.andUsernameEqualTo(username);
		// 执行查询
		List<SysUser> list = sysUserMapper.selectByExample(example);
//		 2、如果不正确，返回登录失败
		if (list == null || list.size() == 0) {
			ajaxResult.put("code", 400);
			ajaxResult.put("msg", "用户名或密码错误！");
			return ajaxResult;
		}
		// 获取用户信息
		SysUser sysUser = list.get(0);
		// 判断密码是否正确
		if (!DigestUtils.sha1DigestAsHex(password).equals(sysUser.getPassword())) {
			ajaxResult.put("code", 400);
			ajaxResult.put("msg", "用户名或密码错误！");
			return ajaxResult;
		}
//		 3、如果正确生成token
		String token = UUID.randomUUID().toString();
//		 4、把用户信息写入redis，key:token value:用户信息
		// 不应该把密码带到客户端
		sysUser.setPassword(null);
		redisTemplate.opsForValue().set("SESSION" + token, JSONObject.toJSONString(sysUser));
//		 5、设置Session的过期时间
		redisTemplate.expire("SESSION" + token, Long.parseLong(SESSION_EXPIRE), TimeUnit.MINUTES);
//		 6、把token返回
		// 返回值：AjaxResult,其中包含token信息，只能返回给表现层
		return new AjaxResult(Type.SUCCESS, "登录成功", token);
	}

}
